
layui.define
(['YsGridBtn', 'YsGridTree', 'soulTable'], function (exports) {
	/* 定义object对象【start】 */
	var object = {
		init:function (c) {this.f(c);this.load();return object;},
		c: {data:[]}, // 配置项
		f: function (c) { // 数据初始化
			var s = new Date().getTime(),t = this;
			if(!c.id_panel_content) {
				alert('页面容器的ID属性未指定，请检查！');
			}
			/* YsGrid基本配置，格式：
			{
				"id_panel_content": "xxxxxxx",
				"conditions": [{}]
			}
			 */
			t.c = c;
			t.c.id = 'id_' + (new Date().getTime());
			t.c.id_panel_content = c.id_panel_content; // 页面容器ID
			t.c.id_grid_panel = 'id_grid_panel_' + (new Date().getTime()); // 主表格所在容器ID
			t.c.id_table_main = 'id_table_main_' + (new Date().getTime()); // 主表格ID
			t.c.id_panel_search_form = 'id_panel_search_form_' + (new Date().getTime()); // 搜索表单所在容器ID
			t.c.id_tree = 'id_tree_' + (new Date().getTime()); // 树ID
			t.c.defaultSortField = 'SortNo'; // 默认排序字段
			t.c.defaultSortType = 'asc'; // 默认排序顺序
			if (t.c.sortType && t.c.sortType == 2) {
				t.c.defaultSortField = 'A.ImportSortNo';
			}
			console.log(t.c.cols);
		},
		load:function () { // 加载控件
			var t = this;
			this.loadHTMLNormal();
			this.loadGridTableMain();
			this.listenBtn();
		},
		loadHTMLNormal: function() {
			var t = this;
			var h =
				 `<!-- 左边面板【start】 -->`
				+ `<div id="` + t.c.id_grid_panel + `" class="ysui-col flex_none width_percent_100">`
					+ `<table class="layui-hide" id="` + t.c.id_table_main + `" lay-filter="` + t.c.id_table_main + `"></table>`
				+ `</div>`
				+ `<!-- 左边面板【end】 -->`;
			$('#'+this.c.id_panel_content).html(h);
		},
		loadGridTableMain:function () { // 加载主表格
			var t = this;
			
			// 创建渲染实例
			layui.table.render({
				elem: '#' + t.c.id_table_main
				,url: t.c.pathGridRequest // 此处为静态模拟数据，实际使用时需换成真实接口
				,toolbar: '#toolbarDemo'
				,defaultToolbar: []
				,height: 'full-0' // 最大高度减去其他容器已占有的高度差
				,where: t.getWhere()
				,cellMinWidth: 95
				,even: false // 开启隔行背景
				,totalRow: false
				,cols: t.c.cols
				,rowDrag: {
					done: function(obj) {
					    var indexOfLoading = layer.load(1, {
					        shade: [0.5,'#000000'] //0.1透明度的白色背景
					    });
						$.ajax({
							type: "POST",
							url: '/api/inter/ysMenu/resortCol',
							data: {
								sortType: t.c.sortType,
								rows: JSON.stringify(layui.table.cache[t.c.id_table_main])
							},
							success: function (data) {
								if (data.code == 0) {
									layer.msg('字段顺序调整成功');
									setTimeout(function(){
										layer.close(indexOfLoading);
										window.location.reload();
									}, 1000);
								} else {
									alert(data.msg);
								}
							}
						});
					}
				}
				,done: function(res){
					var id = this.id;
		            
					// 文本框编辑事件
					$('input[lay-filter="_input_filter_text_on_table"]').on('change',function (e) {
						var table = layui.table;
						var value = $(this).val();
					    var tdElem = $(this).closest('td');
					    var trElem = tdElem.closest('tr');
					    var tableView = trElem.closest('.layui-table-view');
					    table.cache[t.c.id_table_main][trElem.data('index')][tdElem.data('field')] = value;
						
						var dataCommit = {};
						dataCommit['id'] = table.cache[tableView.attr('lay-id')][trElem.data('index')]['id'];
						dataCommit[tdElem.data('field')] = value;
						t.doEditOnTable(dataCommit);
						return;
					});
					
					// 绑定选择框(转换)的值变化提交事件
					layui.form.on('switch(_input_filter_checkbox_on_menu_table)', function(data){
						//layer.tips(this.value + ' ' + this.name + '：'+ data.elem.checked, data.othis);
						var value = this.checked ? 1 : 0;
						t.modifyTableCacheBySwitch(data, value);
					});
					
					// 绑定选择框(下拉)的值变化提交事件
					layui.form.on('select(_input_filter_selector_on_table)', function (data) {
						var table = layui.table;
						
					    var selectElem = $(data.elem);
					    var tdElem = selectElem.closest('td');
					    var trElem = tdElem.closest('tr');
					    var tableView = trElem.closest('.layui-table-view');
					    layui.table.cache[tableView.attr('lay-id')][trElem.data('index')][tdElem.data('field')] = data.value;
						
					    var dataCommit = {};
						dataCommit['id'] = table.cache[tableView.attr('lay-id')][trElem.data('index')]['id'];
						dataCommit[tdElem.data('field')] = data.value;
						t.doEditOnTable(dataCommit);
					});
					// 监听“刷新”按钮
					$('#' + t.c.id_grid_panel).find('div[lay-event="LAYTABLE_REFRESH"]').on('click',function (e) {
						layer.confirm("确定刷新吗？",{
							btn: ['确定', '取消']
						}, function (index) {
							location.reload();
							layer.close(index);
						});
					});
					
					layui.soulTable.render(this);
				}
				,error: function(res, msg){
					console.log(res, msg)
				}
			});

			//触发单元格工具事件
			layui.table.on('tool(main_table)', function(obj){ // 双击 toolDouble
				var data = obj.data;
				//console.log(obj)
				if(obj.event === 'del'){
					layer.confirm('真的删除行么', function(index){
						obj.del();
						layer.close(index);
					});
				} else if(obj.event === 'edit'){
					layer.open({
						title: '编辑',
						type: 1,
						area: ['80%','80%'],
						content: '<div style="padding: 16px;">自定义表单元素</div>'
					});
				}
			});
			
			//触发表格复选框选择
			layui.table.on('checkbox(main_table)', function(obj){
				console.log(obj)
			});
			 
			//触发表格单选框选择
			layui.table.on('radio(main_table)', function(obj){
				console.log(obj)
			});
			 
			// 单元格编辑事件
			layui.table.on('edit(main_table)', function(obj){
				var field = obj.field //得到字段
				,value = obj.value //得到修改后的值
				,data = obj.data; //得到所在行所有键值
				
				var update = {};
				update[field] = value;
				obj.update(update);
				
				var dataCommit = {};
				dataCommit['id'] = data.id;
				dataCommit[field] = value;
				
				doEditOnTable(dataCommit);
			});
			
			// 表格排序事件
			layui.table.on('sort(' + t.c.id_table_main + ')', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
				//尽管我们的 table 自带排序功能，但并没有请求服务端。
				//有些时候，你可能需要根据当前排序的字段，重新向服务端发送请求，从而实现服务端排序，如：
				console.log(obj);
				t.c.defaultSortField = obj.field
				t.c.defaultSortType = obj.type
				layui.table.reload(t.c.id_table_main, {
					//initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。 layui 2.1.1 新增参数
					//,where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
					//	field: obj.field, //排序字段   在接口作为参数字段  field order
					//	order: obj.type //排序方式   在接口作为参数字段  field order
					//}
					where: t.getWhere()
				});
			});
		},
		reloadGrid: function(where) {
			var t = this;
			layui.table.reload(t.c.id_table_main,{
				page: {
					curr: 1 //重新从第 1 页开始
				},
				where: where
			})
		},
		doEditOnTable: function(dataCommit) {
			var t = this;
			var indexOfLoading = layer.load(1, {
				shade: [0.5,'#000000'] //0.1透明度的白色背景
			});
			$.post(t.c.pathGridEditRequest, dataCommit, function(res){
				if (res.code == 0) {
					layer.msg(res.msg);
					layer.close(indexOfLoading);
				} else {
					layer.close(indexOfLoading);
					layer.msg(res.msg);
				}
			});
		},
		modifyTableCacheBySwitch: function(data, value) {
			var t = this;
			
		    var table = layui.table;
		    var switchElem = $(data.elem);
		    var tdElem = switchElem.closest('td');
		    var trElem = tdElem.closest('tr');
		    var tableView = trElem.closest('.layui-table-view');
		    table.cache[tableView.attr('lay-id')][trElem.data('index')][tdElem.data('field')] = value;
			
			var dataCommit = {};
			dataCommit['id'] = table.cache[tableView.attr('lay-id')][trElem.data('index')]['id'];
			dataCommit[tdElem.data('field')] = value;
			t.doEditOnTable(dataCommit);
		},
		listenBtn:function () { // 添加监听
			var t = this;
			
			// 初始化左上角按钮工具栏监听
			layui.YsGridBtn.init({menuId: t.c.menuId, id_table_main: t.c.id_table_main, gridObj: t});
			// 工具栏事件
			layui.table.on('toolbar(' + t.c.id_table_main + ')', function(obj){
				var id = obj.config.id;
				var checkStatus = layui.table.checkStatus(id);
				var datas = checkStatus.data;
				var othis = lay(this);

				switch(obj.event){
					case 'event-grid-add-row':
					{
						$.ajax({
							type: "POST",
							url: '/api/inter/ysCol/addSingle',
							data: {
								menuId: t.c.menuId
							},
							success: function (data) {
								if (data.code == 0) {
									t.reloadGrid();
								} else {
									alert(data.msg);
								}
							}
						});
						break;
					}
					case 'event-grid-add-rows':
					{
						layer.prompt({title: '请填写数据库表名'}, function(value, index, elem){
							if(value === '') {
								return elem.focus();
							} else {
								layer.close(index);
								layer.open({
									type: 2,
									title: "初始化字段",
									area: ['95%', '90%'],
									content: '/web/sys/ysMenu/toBatchAddCol?id=' + t.c.menuId + '&tableName=' + value
								});
							}
						});
						break;
					}
					case '_event-grid-generate-form-html': // 生成表单HTML
					{
						if (datas.length == 0) {
							layer.alert('尚未选中数据');
						} else {
							var ids = '';
							for (var i = 0; i < datas.length; i++) {
								ids = ids + datas[i].id + ',';
							}
							ids = ids.substring(0, ids.length - 1);
							layer.open({
								type: 2,
								title: "生成表单HTML",
								area: ['95%', '90%'],
								content: '/web/sys/ysMenu/toGenerateFormHTML?ids=' + ids
							});
						}
						break;
					}
					case '_13_event-add-row': // 按钮管理-添加按钮
					{
						$.ajax({
							type: "POST",
							url: '/api/inter/ysButton/add',
							data: {
								menuId: t.c.menuId,
								styleType: 1,
								sortNo: 0,
								event: 'eventxxx',
								name: '按钮名称待修改',
								icon: 'iconxxx',
								nameShiroAuth: '权限名称待修改'
							},
							success: function (data) {
								if (data.code == 0) {
									t.reloadGrid();
								} else {
									alert(data.msg);
								}
							}
						});
						break;
					}
					case '_10366_event-add-row': // 下拉按钮管理-添加下拉按钮
					{
						$.ajax({
							type: "POST",
							url: '/api/inter/ysButtonItem/add',
							data: {
								pid: t.c.menuId,
								styleType: 1,
								sortNo: 0,
								event: 'eventxxx',
								name: '按钮名称待修改',
								icon: 'iconxxx',
								nameShiroAuth: '权限名称待修改'
							},
							success: function (data) {
								if (data.code == 0) {
									t.reloadGrid();
								} else {
									alert(data.msg);
								}
							}
						});
						break;
					}
					case '_subgrid_event-add-row': // 子列表管理-新增单个字段
					{
						$.ajax({
							type: "POST",
							url: '/api/inter/ysGridCol/addSingle',
							data: {
								menuId: t.c.menuId
							},
							success: function (data) {
								if (data.code == 0) {
									t.reloadGrid();
								} else {
									alert(data.msg);
								}
							}
						});
						break;
					}
					case '_rowclickgrid_event-add-row': // 行单击列表管理-新增单个字段
					{
						$.ajax({
							type: "POST",
							url: '/api/inter/ysRowClickGridCol/addSingle',
							data: {
								menuId: t.c.menuId
							},
							success: function (data) {
								if (data.code == 0) {
									t.reloadGrid();
								} else {
									alert(data.msg);
								}
							}
						});
						break;
					}
					case '_subgrid_event-add-rows': // 子列表管理-批量新增字段
					{
						layer.prompt({title: '请填写数据库表名'}, function(value, index, elem){
							if(value === '') {
								return elem.focus();
							} else {
								layer.close(index);
								layer.open({
									type: 2,
									title: "初始化字段",
									area: ['95%', '90%'],
									content: '/web/sys/ysGrid/toBatchAddCol?menuId=' + t.c.menuId + '&tableName=' + value
								});
							}
						});
						break;
					}
					case '_subgridbtn_event-add-row': // 子列表按钮-新增单个按钮
					{
						$.ajax({
							type: "POST",
							url: '/api/inter/ysGridButton/addSingle',
							data: {
								menuId: t.c.menuId
							},
							success: function (data) {
								if (data.code == 0) {
									t.reloadGrid();
								} else {
									alert(data.msg);
								}
							}
						});
						break;
					}
				};

			});
	    },
		getData:function () {
			return this.c.conditions;
		},
		setConds:function (conditions) {
			this.c.conditions = conditions;
		},
		getConds:function (type) { // 类型，空或1代表直接取对象里的值，2代表去前端重新获取
			var t = this;
			var conditionsRes = [];
			$('#' + t.c.id_panel_search_form).find('[data-form-filter="ys-search-form-item"]').each(function(){
				var v = $(this).val();
				if(v) {
					var i = $(this).attr('data-index');
					var condition = t.c.conditions[i];
					conditionsRes.push({'rangeType':condition.rangeType, 'value': v, 'field':condition.code});
				}
			});
			
			if (type == 2) {
				return {'conditions': JSON.stringify(conditionsRes)}
			} else {
				return conditionsRes;
			}
		},
		getOrderby:function () { // 获取排序字段
			var t = this;
			return t.c.defaultSortField + ' ' + t.c.defaultSortType;
		},
		getWhere:function () { // 获取请求参数
			var t = this;
			return {'conditions': JSON.stringify(t.getConds()), 'orderby': t.getOrderby()};
		}
	};
	/* 定义object对象【end】 */
	
	exports('YsGridOfMainTable', object);
});

function doDeleteOnTable(url) {
    var indexOfLoading = layer.load(1, {
        shade: [0.5,'#000000'] //0.1透明度的白色背景
    });
    layer.confirm('确定删除？ ', {
            btn: ['确定','取消'] //按钮
        }, function(){
            $.post(url, function(res){
                if (res.code == 0) {
                    layer.msg(res.msg);
                    layer.close(indexOfLoading);
                    location.reload();
                } else {
                    layer.close(indexOfLoading);
                    layer.msg(res.msg);
                }
            });
        }, function(){
            layer.close(indexOfLoading);
        }
    );
}

// 进入表单页
function toFlow(bid, title) {
    $.ajax({
        type: "POST",
        url: '/api/inter/ysProcInst/getMenuIdByBid',
        data: {bid: bid},
        success: function (res) {
        	console.log(res);
        	var menuId = null;
            if (res.code == 0) {
            	menuId = res.data;
            } else {
                alert('加载页面失败，请检查菜单的流程配置');
            }
            /*
             * 此处根据不同菜单ID，跳转不同的表单页
             */
            if (menuId == 51) {//运营公司备案
				openUrl(title,"/web/hr/thrOperateCompanyBeian/toEdit?bid="+bid);
			} else if (menuId == 70) {
            	openUrl(title, '/web/finance/tcwRunningBack/toFlow?bid=' + bid);
			} else if (menuId == 10166) {//印章申请
				openUrl(title, '/web/administration/webAdmUseSignetApplyController/toEdit?bid=' + bid);
			} else if (menuId == 10169) {
				openUrl(title, '/web/business/tpProductBq/toEdit?bid=' + bid);
			}else if(menuId == '10178'){
				openUrl(title, '/web/business/tpProductActiveSq/toEdit?bid=' + bid);
			}else if(menuId == '10180'){
				openUrl(title, '/web/business/tpAplusSq/toEdit?bid=' + bid);
			}else if (menuId == 10199) {
            	openUrl(title, '/web/storage/tccAllocate/toFlow?bid=' + bid);
			} else if (menuId == 10201) {//运营人员登记
				openUrl(title, '/web/hr/thrOperateRegistration/toEdit?bid=' + bid);
			} else if (menuId == 10205) {//人员申请
				openUrl(title, ' /web/hr/thrUserEntryApply/toEdit?bid=' + bid);
			} else if (menuId == 10206) {
            	openUrl(title, '/web/storage/tccDistribute/toFlow?bid=' + bid);
			} else if (menuId == 10207) {
				openUrl(title, '/web/storage/tccAllocateCancel/toFlow?bid=' + bid);
			} else if (menuId == 10258) {
				openUrl(title, '/web/hr/twlStockBorrow/toFlow?bid=' + bid);
			} else if (menuId == 10263) {
				openUrl(title, '/web/base/tbUserMonthPerformanceReport/toEdit?bid=' + bid);
			}else if (menuId == 10264) {//员工工资申请单
				openUrl(title, '/web/base/tbUserPayApply/toEdit?bid=' + bid);
			}else if (menuId == 10269) {//工资付款单
				openUrl(title, '/web/base/tbPayrollSlip/toEdit?bid=' + bid);
			}else if (menuId == 10270) {//医保付款单
				openUrl(title, '/web/base/tbMedicarePay/toEdit?bid=' + bid);
			}else if (menuId == 10271) {//社保付款单
				openUrl(title, '/web/base/tbSocialSecurityPay/toEdit?bid=' + bid);
			}else if (menuId == 10272) {//公积金付款单
				openUrl(title, '/web/base/tbReservedPay/toEdit?bid=' + bid);
			}else if (menuId == 10273) {//个税付款单
				openUrl(title, '/web/base/tbIncomePay/toEdit?bid=' + bid);
			} else if (menuId == 10213) {//招商信息申请
				openUrl(title,"/web/business/thrCanvassApply/toEdit?bid="+bid);
			} else if (menuId == 10282) {//预支账户充值单
				openUrl(title, '/web/account/tcwAdvanceAccountRecharge/toEdit?bid=' + bid);
			} else if (menuId == 10283) {//预支账户报销单
				openUrl(title, "/web/account/tcwAdvanceAccountReimbursement/toEdit?bid=" + bid);
			} else if (menuId == 10291) {//预支账户归还单
				openUrl(title, '/web/account/tcwAdvanceAccountBack/toEdit?bid=' + bid);
			}   else {
				alert('请先设置好表单页面路径');
			}
        }
    });
}

function openUrl(title, url, toType) { // toType，打开页面方式，1标签页2新页面
	
	if (!window.top.is_on_1_5) {
		window.open(url);
	} else {
		window.top.add_tab(title, url);
	}
}